#include "stdafx.h"
#include "jssocket.h"
#include "jsiomodel.h"

/***************************************************
 *
 * 返回值
 * 	成功：非负的socket描述符
 * 	失败：-1
 * *************************************************/
int JS_TCPServer(int nPort, int nMaxConnectNum)
{
	static bool inited = false;

	if(!inited)
	{
		//signal(SIGPIPE,SIGPipeHandler);
		inited = true;
	}

    int servfd = -1;
    //g_nMaxConnectNum = nMaxConnectNum;

    if (nPort <= 0 || nMaxConnectNum <=0)
    {
        return -1;
    }

    servfd = Socket(AF_INET, SOCK_STREAM, 0);
    if (servfd == -1)
	{
		return -1;
	}
    int on = 1;
    setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    struct sockaddr_in servAddr;

    servAddr.sin_family       = AF_INET;
    servAddr.sin_port        = htons(nPort);
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    bzero(&(servAddr.sin_zero), 8);

	if (Bind(servfd, (struct sockaddr *)&servAddr, sizeof(struct sockaddr)) == -1)
	{
		Close(servfd);
		return -1;
	}

	if (Listen(servfd, nMaxConnectNum) == -1)
	{
		Close(servfd);
		return -1;
	}

	return servfd;
}



//返回client fd
int JS_TCPClient(char *pIPAddr, int nPort)
{
    int clientfd = -1;

    if (pIPAddr==NULL || nPort<=0)
    {
        return -1;
    }

    clientfd = Socket(AF_INET, SOCK_STREAM, 0);
	if (clientfd == -1)
	{
		return -1;
	}

    struct sockaddr_in servAddr;
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(nPort);
    servAddr.sin_addr.s_addr = inet_addr(pIPAddr);
    bzero(&(servAddr.sin_zero), 8);

    if (Connect(clientfd, (struct sockaddr *)&servAddr, sizeof(struct sockaddr)) == -1)
    {
    	Close(clientfd);
    	return -1;
    }

    return clientfd;
}


int JS_UDPServer(int nPort)
{
    int servfd = -1;

    if (nPort <= 0)
    {
        return -1;
    }

    servfd = Socket(AF_INET, SOCK_DGRAM, 0);
    if (servfd == -1)
	{
		return -1;
	}

    struct sockaddr_in servAddr;

    servAddr.sin_family       = AF_INET;
    servAddr.sin_port        = htons(nPort);
    servAddr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(servAddr.sin_zero), 8);


	if (Bind(servfd, (struct sockaddr *)&servAddr, sizeof(struct sockaddr)) == -1)
	{
		return -1;
	}

	return servfd;
}


int JS_UDPClient()
{
    int servfd = -1;

    servfd = Socket(AF_INET, SOCK_DGRAM, 0);
    if (servfd == -1)
	{
		return -1;
	}

    return servfd;
}


//实现socket API为包裹函数
/***************************************************
 *
 * 返回值
 * 	成功：非负的socket描述符
 * 	失败：-1
 * *************************************************/
int Socket(int family, int type, int protocol)
{
	int serverfd = socket(family, type, protocol);
	if (serverfd < 0)
	{
		perror("create socket:");
		return -1;
	}

	return serverfd;
}


/***************************************************
 *
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int Bind(int sockfd, struct sockaddr *addr, int addrlen)
{
	if (bind(sockfd, addr, addrlen) == -1)
	{
		perror("bind:");
		return -1;
	}

	return 0;
}


/***************************************************
 *
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int Listen(int sockfd, int maxConnectNum)
{
	if (listen(sockfd, maxConnectNum) == -1)
	{
		perror("listen");
		return -1;
	}

	return 0;
}


/***************************************************
 *
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int Connect(int sockfd, struct sockaddr *serv_addr, int addrlen)
{
	if (connect(sockfd, serv_addr, addrlen) == -1)
	{
		perror("connect");
		return -1;
	}

	return 0;
}


/***************************************************
 *
 * 返回值
 * 	成功：接收到的客户端的socket fd
 * 	失败：-1
 * *************************************************/
int Accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
	int clientfd = -1;
	if ((clientfd = accept(sockfd, addr, addrlen)) == -1)
	{
		perror("accept");
		return -1;
	}

	return clientfd;
}


/***************************************************
 *
 * 返回值
 * 	成功：发送的字节数
 * 	失败：-1
 * *************************************************/
int Send(int sockfd, char *pBuf, int len)
{
	return send(sockfd, pBuf, len, 0);
}


/***************************************************
 *
 * 返回值
 * 	成功：接收的字节数，并将数据存放在pBuf中
 * 	失败：-1
 * *************************************************/
int Recv(int sockfd, char *pBuf, int len)
{
	int nTempLen = recv(sockfd, pBuf, len, 0);

    //cout<<"socket recv N type:	"<<*(int *)pBuf<<endl;
    //cout<<"socket recv N len: "<<*(int *)(pBuf+4)<<endl;

    return nTempLen;
}


int Sendto(int sockfd, char *pBuf, int len, int flag, struct sockaddr *to, int tolen)
{
	return sendto(sockfd, pBuf, len, flag, to, tolen);
}

int Recvfrom(int sockfd, char *pBuf, int len, int flag, struct sockaddr *from, socklen_t *fromlen)
{
	return recvfrom(sockfd, pBuf, len, flag, from, fromlen);
}

/***************************************************
 *
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int Close(int sockfd)
{
	if (close(sockfd) == -1)
	{
		perror("close");
		return -1;
	}

	return 0;
}



/***************************************************
 * 描述
 *	关闭文件描述符，如果是client fd,则还要从文件描述符队列中清除掉
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int EndSocket(int nFd)
{
/*
	if (Close(nFd) == -1)
	{
		return -1;
	}

	for (int i=0; i<m_nMaxConnectNum; i++)
	{
		if (client[i] == -1)
		{
			continue;
		}

		if (client[i] == nFd)
		{
			client[i] = -1;
			break;
		}
	}
*/
	return 0;
}


//=============================================
//函数说明：读取指定长度len，数据存储到pBuf中，返回实际的读取长度。
//也说是是说，读不到实际的长度<=len。每次读到0长度为0或－1则为出错了 。
//=============================================
int RecvData(int nFd, char *pBuf, int nLen)
{
    return Recv(nFd, pBuf, nLen);
}

//==============================================
//函数说明：读取指定长度len，数据存储到pBuf中，返回实际的读取长度，
//如果读到不指定长度，则阻塞等待。每次读到0长度为0或－1则为出错了 。并清空pBuf
//==============================================
int RecvDataN(int nFd, char *pBuf, int nLen)
{
    if ((pBuf == NULL) || (nLen == 0))
    {
        return -1;
    }

    char *pTempBuf = new char[nLen];
    memset(pTempBuf, 0, nLen);

    int nRecvLen = 0;   //每次接收长度之和
    int nTempLen = 0;   //每次接收长度


    while (nRecvLen < nLen)
    {
        memset(pTempBuf, 0, nLen);

        nTempLen = RecvData(nFd, pTempBuf, nLen-nRecvLen);
        if (nTempLen <= 0)
        {
            delete[] pTempBuf;
            return nTempLen;
        }

        //把接收到的数据连接起来，存储到pBuf中
        //strcat(pBuf, pTempBuf);
        for (int i=0; i<nTempLen; i++)
        {
        	pBuf[nRecvLen+i] = pTempBuf[i];
        }

        //计算每次接收长度之和
        nRecvLen += nTempLen;
        //cout<<"recv N type tempbuf: "<<*(int *)pTempBuf<<endl;
        //cout<<"recv N len: tempbuf"<<*(int *)(pTempBuf+4)<<endl;

        //cout<<"recv N type: buf"<<*(int *)pBuf<<endl;
        //cout<<"recv N len: buf"<<*(int *)(pBuf+4)<<endl;
    }

    delete[] pTempBuf;

    return nRecvLen;
}

//ReadPackage(int nFd, char *pBuf);



/***************************************************
 * 描述
 *	发送nLen个字节，实际发送的字节数<=要发送的字节数
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int SendData(int nFd, char *pBuf, int nLen)
{
    return Send(nFd, pBuf, nLen);
}



/***************************************************
 * 描述
 *	阻塞发送nLen个字节，要确保实际发送的字节数=要发送的字节数
 * 返回值
 * 	成功：0
 * 	失败：-1
 * *************************************************/
int SendDataN(int nFd, char *pBuf, int nLen)
{
    char *p = pBuf;
    int nSendLen = 0;   //每次发送长度之和
    int nTempLen = 0;   //每次发送长度

    while (nSendLen < nLen)
    {
    	//printf("SendData begin!!!\n");

        nTempLen = SendData(nFd, p, nLen-nSendLen);
        if (nTempLen <= 0)
        {
            return nTempLen;
        }

        //printf("SendData %d ok!!!\n", nLen);

        //计算总发送长度
        nSendLen += nTempLen;

        //发送指针后移
        p += nTempLen;
    }

    return nSendLen;
}

//发送整个数据包
int SendMsg(int nFd, CJSMsg &msg)
{
	return SendDataN(nFd, msg.GetMsg(), msg.MsgLength());
}

//接收一个完整的数据包,返回一个数据包的长度
int RecvMsg(int nFd, CJSMsg &msg)
{
	int nRecvLen = 0;
	int nType = 0;
	int nPackLen = 0;

	char str[8];
	memset(str, 0, sizeof(str));

	//接收数据头(TL，共8个字节)
	nRecvLen = RecvDataN(nFd, str, 8);
	if (nRecvLen > 0)
	{
		//取类型(T)
		int *pType = (int *)str;
		nType = *pType;

		//取长度(L)
		int *pPackLen = (int *)(str+4);
		nPackLen = *pPackLen;

		//放入数据包
		if (msg.PutMsg(str, 8) == -1)
		{
			return -1;
		}
	}
	else
	{
		printf("recv TL. length=%d---TL\n", nRecvLen);
		return nRecvLen;
	}

	if (nPackLen < 0)
	{
		printf("unpack TL. length=%d\t---TL\n", nPackLen);
		return -1;
	}

	if (nPackLen == 0)
	{
		return 8;
	}


	//接收数据(L)
	char *pValue = new char[nPackLen];
	memset(pValue, 0, nPackLen);
	nRecvLen = RecvDataN(nFd, pValue, nPackLen);
	if (nRecvLen > 0)
	{
		if (msg.PutMsg(pValue, nPackLen) == -1)
		{
			if (pValue != NULL)
			{
				delete[] pValue;
				pValue = NULL;
			}
			return -1;
		}
	}
	else
	{
		printf("recv V. length=%d\t---V\n", nRecvLen);

		if (pValue != NULL)
		{
			delete[] pValue;
			pValue = NULL;
		}

		return nRecvLen;
	}

	if (pValue != NULL)
	{
		delete[] pValue;
		pValue = NULL;
	}

	return nRecvLen+8;

}

int SendMsgTo(int nFd, CJSMsg &msg, struct sockaddr_in *to)
{
	if (to == NULL)
	{
		return -1;
	}

	return SendTo(nFd, msg.GetMsg(), msg.MsgLength(), to);
}


int RecvMsgFrom(int nFd, CJSMsg &msg, struct sockaddr_in *from)
{
	char buf[256];
	int rlen = RecvFrom(nFd, buf, 256, from);
	if (rlen < 0)
	{
		return -1;
	}
	msg.PutMsg(buf, rlen);

	return rlen;

	/*
	char str[8];
	int rlen = 0;
	rlen = RecvFrom(nFd, str, 8, from);
	if (rlen < 0)	//能等于0不？
	{
		return rlen;
	}

	//取L
	int *pPackLen = (int *)(str+4);
	int L = *pPackLen;

	msg.PutMsg(str, 8);

	if (L == 0)
	{
		return 8;
	}

	if (L > 0)
	{
		char *value = new char[L];
		rlen = RecvFrom(nFd, value, L, from);
		if (rlen < 0)	//能等于0不？
		{
			if (value != NULL)
			{
				delete value;
				value = NULL;
			}
			return rlen;
		}
		msg.PutMsg(value, L);

		if (value != NULL)
		{
			delete value;
			value = NULL;
		}
	}

	return L+8;*/
}


int SendTo(int sockfd, char *pBuf, int len, struct sockaddr_in *to)
{
	return Sendto(sockfd, pBuf, len, 0, (struct sockaddr *)to, sizeof(struct sockaddr));
}
int RecvFrom(int sockfd, char *pBuf, int len, struct sockaddr_in *from)
{
	if (from == NULL)
	{
		return Recvfrom(sockfd, pBuf, len, 0, NULL, NULL);
	}
	else
	{
		socklen_t fromlen;
		return Recvfrom(sockfd, pBuf, len, 0, (struct sockaddr*)from, &fromlen);
	}
}


//data指向的数据由上层释放
//将TLV转换成以下数据包格式。注TLV中的V值为：len(4字节) data(=以下的value)
//数据包格式：
//0xaa55aa55	length		value
//4				4			length
//返回config socket发送包的长度 = 4 + 4 + length
int TLVtoConfigNetPackage(CJSMsg &msg, BYTE **data)
{
	//int type = msg.Type();
	int L = msg.Length();

	BYTE *value = new BYTE[L+4];
	if (value == NULL)
	{
		return -1;
	}

	msg.UnPackBegin();
	int len = msg.GetByteArray()->GetInt();
	//printf("TLVtoNetPackage   jpeg and head len=%d\n", len+8);
	msg.GetByteArray()->GetByte(value, len);

	for (int i=len-1; i>=0; i--)
	{
		value[i+8] = value[i];
	}

	unsigned int a[2];
	a[0] = 0x55aa55aa;
	a[1] = len;
	unsigned int *packhead = (unsigned int *)value;
	*packhead = a[0];

	unsigned int *pLen = (unsigned int *)(value+4);
	*pLen = a[1];

	*data = value;

	return len+8;
}

//将TLV包转换成以下数据包格式.注：TLV包中的V值为:len(4字节) data(从类型到校验码)
//数据包格式:
//0x55aa	类型		长度(length)		Value		校验码	0xaa55
//2			1		2				length		1		2
//返回值= 2 + 1 + 2 + length + 1 + 2
int TLVtoResultNetPackage(CJSMsg &msg, BYTE** data)
{
	msg.UnPackBegin();

	BYTE head;
	msg.GetByteArray()->GetByte(head);			//head
	short len = ntohs(msg.GetByteArray()->GetShort());		//length

	BYTE *value = new BYTE[len+8];
	if (value == NULL)
	{
		return -1;
	}
	msg.GetByteArray()->GetByte(value, len);	//value

	BYTE check;
	msg.GetByteArray()->GetByte(check);			//check

	//封装result socket的包
	value[len+5] = check;
	value[len+6] = 0xaa;
	value[len+7] = 0x55;

	for (int i=len-1; i>=0; i--)
	{
		value[i+5] = value[i];
	}

	value[0] = 0x55;
	value[1] = 0xaa;
	value[2] = head;
	//value 长度
	long *length = (long*)(value+3);
	*length = htons(len);

	*data = value;

//	printf("\n\nTLV. device id=%d\n", ntohl(*(int*)(*data+5)));
//	printf("TLV. time=%ld\n", ntohl(*(long*)(*data+9)));

	return len+8;
}

int SendMsg_Net(int nFd, char *pBuf, int nLen)
{
	return SendDataN(nFd, pBuf, nLen);
}

//返回的长度为pBuf中数据的长度
//数据包格式：
//0xaa55aa55	length		value
//4				4			length
int RecvMsg_ConfigNet(int nFd, char *pBuf)
{
	if (pBuf == NULL)
	{
		return -1;
	}
#ifdef RECV_SAME
	//printf("RecvMsg_DebugNet. fd=%d\n", nFd);
	static unsigned char buffer[SIZE];
	static int recvStart = 0;			//开始填冲数据的下标
	static int getStart = 0;			//开始接收数据的下标
	static int nPackNum = 0;

	char buf[SIZE];
	int rlen = 0;

	while (nPackNum <= 0)
	{
		//printf("RecvData begin.\n");
		rlen = RecvData(nFd, buf, 512*1024);

		//rlen = RecvDataN(nFd, buf, 32);
		//printf("RecvMsg_DebugNet. rlen=%d\n", rlen);
		if (rlen <= 0)
		{
			memset(buffer, 0, SIZE);
			recvStart = 0;
			getStart = 0;
			nPackNum = 0;
			return rlen;
		}

		for (int i=0; i<rlen; i++)
		{
			buffer[(recvStart+i)%SIZE] = buf[i];
		}

		recvStart = (recvStart + rlen)%SIZE;

		//nPackNum = PackNum(buffer, SIZE);
		int num = 0;
		for (int i=0; i<SIZE; i++)
		{
			if((buffer[i] == 0xaa) && (buffer[(i+1)%SIZE] == 0x55) &&
						(buffer[(i+2)%SIZE] == 0xaa) && (buffer[(i+3)%SIZE] == 0x55))
			{
				num++;
			}
		}

		nPackNum = num;

	}



	unsigned int dataLen;

	char* p = (char*)&dataLen;
	p[0] = buffer[(getStart+4)%SIZE];
	p[1] = buffer[(getStart+5)%SIZE];
	p[2] = buffer[(getStart+6)%SIZE];
	p[3] = buffer[(getStart+7)%SIZE];
	//printf("RecvMsg_DebugNet. dataLen=%d\n", dataLen);

    char b[1024];
	for (int i=0; i<dataLen; i++)
	{
		pBuf[i] = buffer[(getStart+8+i)%SIZE];
		b[i] = buffer[(getStart+8+i)%SIZE];

	}

	getStart = (getStart + dataLen + 8)%SIZE;

	nPackNum--;

	return dataLen;
#endif

	char tempBuf[8];
	int rlen = 0;
	rlen = RecvDataN(nFd, tempBuf, 8);
	if (rlen <= 0)
	{
		printf("RecvMsg_ConfigNet...recv msg config socket--8. len=%d\n", rlen);
		return rlen;
	}

	unsigned int dataLen;

	char* p = (char*)&dataLen;
	p[0] = tempBuf[4];
	p[1] = tempBuf[5];
	p[2] = tempBuf[6];
	p[3] = tempBuf[7];

	//char *buffer = new char[dataLen];
	rlen = RecvDataN(nFd, pBuf, dataLen);
	if (rlen <= 0)
	{
		printf("RecvMsg_ConfigNet...recv msg config socket--value\n");
		return rlen;
	}

	return dataLen;
}

//返回的长度为pBuf中数据的长度
//数据包格式:
//0x55aa	类型		长度(length)		Value		校验码	0xaa55
//2			1		2				length		1		2
int RecvMsg_ResultNet(int nFd, char *pBuf)
{
	if (pBuf == NULL)
	{
		return -1;
	}
#ifdef RECV_SAME
	//printf("RecvMsg_DebugNet. fd=%d\n", nFd);
	static unsigned char buffer[SIZE];
	static int recvStart = 0;			//开始填冲数据的下标
	static int getStart = 0;			//开始接收数据的下标
	static int nPackNum = 0;

	char buf[SIZE];
	int rlen = 0;

	while (nPackNum <= 0)
	{
		//printf("RecvData begin.\n");
		rlen = RecvData(nFd, buf, 512*1024);

		//rlen = RecvDataN(nFd, buf, 32);
		//printf("RecvMsg_DebugNet. rlen=%d\n", rlen);
		if (rlen <= 0)
		{
			memset(buffer, 0, SIZE);
			recvStart = 0;
			getStart = 0;
			nPackNum = 0;
			return rlen;
		}

		for (int i=0; i<rlen; i++)
		{
			buffer[(recvStart+i)%SIZE] = buf[i];
		}

		recvStart = (recvStart + rlen)%SIZE;

		//nPackNum = PackNum(buffer, SIZE);
		//可能有问题
		int num = 0;
		for (int i=0; i<SIZE; i++)
		{
			if((buffer[i] == 0xaa) && (buffer[(i+1)%SIZE] == 0x55))
			{
				num++;
			}
		}

		nPackNum = num;

	}

	int dataLen = 0;
	//m_recvBuffer[(m_recvStart+2)%SIZE]放的是包类型
	if(buffer[(getStart+2)%SIZE] == 0)        //心跳信号
	{
		unsigned char p0, p1, p2, p3;
		p0 = buffer[(getStart+2)%SIZE];
		p1 = buffer[(getStart+3)%SIZE];
		p2 = buffer[(getStart+4)%SIZE];
		p3 = buffer[(getStart+5)%SIZE];

		if(!p0 && !p1 && !p2 && (p3== 0xff))
		{
			for (int i=0; i<8; i++)
			{
				pBuf[i] = buffer[(getStart+2+i)%SIZE];
			}

			//加一整个心跳包长度
			getStart = (getStart+8)%SIZE;

			printf("get a hello from net\n");
		}

		dataLen = 4;
	}
	else
	{
		short length;           //暂时定义数据长度为两个字节的short类型
		short *pNetLength = (short*)(getStart + (getStart+3)%SIZE);
		length = ntohs(*pNetLength);

		for (unsigned int i=0; i<length+4; i++)
		{
			pBuf[i] = buffer[(getStart + 2 + i) % SIZE];
		}
		getStart = (getStart+8+length)%SIZE;

		dataLen = length+4;
	}

	nPackNum--;
	return dataLen;
#endif

	char tempBuf[5];
	int rlen = 0;
	rlen = RecvDataN(nFd, tempBuf, 5);
	//printf("RecvMsg_Net. RecvDataN. len=%d\n", rlen);
	if (rlen <= 0)
	{
		printf("RecvMsg_ResultNet...recv msg result socket--5\n");
		return rlen;
	}

	int rtLen = 0;

	//buf[2]为类型
	if (tempBuf[2] == 0)
	{
		rlen = RecvDataN(nFd, tempBuf, 3);
		if (rlen <= 0)
		{
			printf("RecvMsg_ResultNet...recv msg result socket--3\n");
			return rlen;
		}

		//心跳包数据
		pBuf[0] = 0x00;
		pBuf[1] = 0x00;
		pBuf[2] = 0x00;
		pBuf[3] = 0xff;

		rtLen = 4;
	}
	else
	{
		short length; //暂时定义数据长度为两个字节的short类型
		short *pNetLength = (short*) (tempBuf+3);
		length = ntohs(*pNetLength);

		char *t = new char[length+3];
		if (t == NULL)
		{
			return -1;
		}

		rlen = RecvDataN(nFd, t, length+3);
		if (rlen <= 0)
		{
			printf("RecvMsg_Result...recv msg result net--last\n");
			return rlen;
		}

		int i=0;
		//类型，长度
		for (i=0; i<3; i++)
		{
			pBuf[i] = tempBuf[2+i];
		}

		//value，校验码
		for (i=0; i<length+1; i++)
		{
			pBuf[3+i] = t[i];
		}

		if (t != NULL)
		{
			delete[] t;
			t = NULL;
		}

		rtLen = length + 4;
	}

	return rtLen;
}


int PackNum(char *buffer, int length)
{
	int num = 0;
	if (buffer == NULL)
	{
		return 0;
	}

	if (length < 4)
	{
		return 0;
	}

	for (int i=0; i<length; i++)
	{
		/*
		if((buffer[i] == 0xaa) && (buffer[(i+1)%SIZE] == 0x55) &&
					(buffer[(i+2)%SIZE] == 0xaa) && (buffer[(i+3)%SIZE] == 0x55))

		{
			num++;
		}*/
	}

	return num;
}

int JS_OnAccept(int nFd, int eventID, void *param)
{
	struct sockaddr_in clientAddr;
    socklen_t clientLength = sizeof(clientAddr);

	int nConFd = Accept(nFd, (struct sockaddr *) &clientAddr, &clientLength);

	//printf("current connect num:%d\n", g_nCurConnectNum);
	//printf("max connect num:%d\n", g_nMaxConnectNum);

//    if (g_nCurConnectNum < g_nMaxConnectNum)
//    {
	if (nConFd != -1)
	{
        printf("accept IP %s	Port %d\t", inet_ntoa(clientAddr.sin_addr), clientAddr.sin_port);
        cout<<"accept fd:"<<nConFd<<endl;

        if (param != NULL)
        {
        	strcpy((char *)param, inet_ntoa(clientAddr.sin_addr));
        }
	}
	else
	{
		printf("Accept. fd=%d\n", nConFd);
	}
        //g_nCurConnectNum++;
	return nConFd;
//	}
//	else
//	{
//	    printf("refuse connect. IP %s\n", inet_ntoa(clientAddr.sin_addr));
//	    return -1;
//	}
}

/*
int JS_OnConnect(int nfd, int event, void *)
{
	int rt = 0;
	switch (event)
	{
	case JSREADEVENT:
		rt = JS_OnAccept(nfd, event, NULL);
		break;
	case JSWRITEEVENT:
	case JSEXCEPTIONEVENT:
	default:
		break;
	}

	return rt;
}
int JS_Net(int nfd, int event, void *)
{
	int rt = 0;
	switch (event)
	{
	case JSREADEVENT:
		rt = JS_OnRecv(nfd, event, NULL);
		break;
	case JSWRITEEVENT:
		rt = JS_OnSend(nfd,event,NULL);
		break;
	case JSEXCEPTIONEVENT:
	default:
		break;
	}

	return rt;
}
//返回一个完整数据包的长度
int JS_OnRecv(int nFd, int eventID, void *param)
{
	static int nPackCount = 1;

	CJSMsg msg;
	int n = RecvMsg(nFd, msg);
	if (n <= 0)
	{
		printf("recv msg. length=%d\n", n);
		g_nCurConnectNum--;
		return n;
	}

	int nType = msg.Type();
	int nLen = msg.Length();
	BYTE byte[1024*1024*4];
	msg.GetByteArray()->GetByte(byte, msg.Length());

	printf("unpack data. type=%d\t\tlength=%d\t\tpackcount=%d\n", nType, nLen, nPackCount);

	nPackCount++;

    return n;
}



int JS_OnSend(int nFd, int eventID, void *param)
{
	//return 1;
	//static int nCount = 0;
	static int nPackCount = 1;
	static int nType = 1;
	static int nPackLen=1024*1024;
	//int len = 0;
	int nSend = 0;
	if (1)
	{
		BYTE str[1024*1024*4] ;
		memset(str, 0, sizeof(str));

		if (nPackLen > 1024*1024*4)
		{
			nPackLen = 1024*1024;
		}

		memset(str, 'a', nPackLen);

		Package pack;
		pack.nType = nType;
		pack.nLen = nPackLen;
		pack.pBuffer = str;

		CJSMsg msg(pack.nType, pack.nLen);
		msg.GetByteArray()->PutByte(pack.pBuffer, pack.nLen);
		msg.End();

		nSend = SendMsg(nFd, msg);
		if (nSend < 0)
		{
			printf("send msg. length=%d\n", nSend);
			g_nCurConnectNum--;
			return nSend;
		}

		//构建写文件数据
		char strWrite[128];
		memset(strWrite, 0, 128);
		sprintf(strWrite, "send data. type=%d\t\tlength=%d\n", pack.nType, pack.nLen);
		printf("%s", strWrite);

		//构建文件名
		char strfilename[32];
		memset(strfilename, 0, 32);
		sprintf(strfilename, "%d.txt", nFd);
	}
	//nCount++;
	nPackCount++;
	nType++;
	nPackLen++;
	return nSend;
}
*/

